package com.aoxun.core.cos;

import com.alibaba.fastjson.JSONObject;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.request.UploadFileRequest;
import com.qcloud.cos.sign.Credentials;

public class CosUtils {

	private static COSClient cosClient;
	
	public static COSClient getCOSClient() {
		if (cosClient == null) {
			synchronized (CosUtils.class) {
				if (cosClient == null) {
					cosClient = new COSClient(CosConfig.getAppId(),
							CosConfig.getSecretId(), CosConfig.getSecretKey());
					Credentials cred = new Credentials(CosConfig.getAppId(), CosConfig.getSecretId(), CosConfig.getSecretKey());
					ClientConfig clientConfig = new ClientConfig();
			        clientConfig.setRegion("sh");
			        cosClient = new COSClient(clientConfig, cred);
				}
			}
		}
		return cosClient;
	}
	
	/**
	 * 文件上传
	 * @param localFilePath
	 * @param cosFilePath
	 * @return
	 */
	public static JSONObject uploadFiles(String localFilePath,String cosFilePath) {
		//连接COS 服务器
		COSClient cosClient = CosUtils.getCOSClient();
		JSONObject resultJson=new JSONObject();
		UploadFileRequest uploadFileRequest = new UploadFileRequest(CosConfig.getBucket(), cosFilePath, localFilePath);
		String uploadFileRet = cosClient.uploadFile(uploadFileRequest);
		JSONObject json=JSONObject.parseObject(uploadFileRet);
		System.out.println(json.toJSONString());
		if("0".equals(json.getString("code"))) {
			resultJson=json.getJSONObject("data");
			//accessUrl=object.getString("access_url");
		}
		return resultJson;
	}

}
